import axios from 'axios'
import store from '@/store'
import storage from 'store'
import router from '@/router'
import notification from 'ant-design-vue/es/notification'
import {
  message
} from 'ant-design-vue'

import {
  VueAxios
} from './axios'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'
import aes from './aes.js'
import rsa from './rsa.js'
import { apiUrl } from './branch'
// 创建 axios 实例
console.log(process.env.NODE_ENV == 'development','aaaaaaaaaaaa')

const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.NODE_ENV == 'development' ? '//192.168.2.34:6677/' : apiUrl,//'',
  timeout: 60000 // 请求超时时间
})


function dt(data) {
  for (let i in data) {
    if(data[i] === '' || data[i] === null || data[i] === undefined)
    delete data[i]
  }
  return data
}

function commonFun(config) {
  console.log(config.data, config.url)
  var data = JSON.stringify(dt(config.data))
  var string = aes.randomString(16)
  var params = {
    key: rsa.RSAencrypt(string),
    data: aes.Encrypt(data || null, string),
    defaultKey: string
  }
  // var params = {
  //   key: rsa.RSAencrypt(string),
  //   data: data,//aes.Encrypt(data || null, string),
  //   defaultKey: string
  // }
  return params
}

function GetQueryString(str) {
  var str = JSON.parse(str);
  return str.key
}

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  if (config.data && config.data.pageNo) {
    config.data.pageNum = config.data.pageNo;
    delete config.data.pageNo;
  }
  if (config.data && config.data.current) {
    config.data.pageNum = config.data.current;
    delete config.data.current;
  }
  if (config.data && config.data.sortField) {
    let sortJ = config.data.sortJ;
    config.data.orderBy = sortJ[config.data.sortField]
    delete config.data.sortField
    config.data.sortOrder == 'descend' ? config.data.bySort = 'desc' : ''
    config.data.sortOrder == 'ascend' ? config.data.bySort = 'asc' : ''

    console.log(JSON.parse(JSON.stringify(config.data)),'config.data')
    config.data.order == 'descend' ? config.data.bySort = 'desc' : ''
    config.data.order == 'ascend' ? config.data.bySort = 'asc' : ''

    delete config.data.order
    delete config.data.sortOrder
    delete config.data.sortJ
  }
  config.headers['Content-Type'] = 'application/json';
  const commonData = commonFun(config)
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  // 加入'application/json'
  if (token) {
    // config.headers['token'] = token
    config.headers['token'] = aes.Encrypt(token + '' + new Date().getTime(), commonData.defaultKey)
  }else{
    // 没token 加密当前时间戳
    let aesToken = aes.Encrypt(new Date().getTime(), commonData.defaultKey)
    config.headers['token'] = aesToken
  }
  delete commonData.defaultKey

  config.data = commonData
  // config.data = commonData.data
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  // if the custom code is not 20000, it is judged as an error.
  const res = response.data
  if (response.status == 200 && (response.data.code == 1)) {
    //  解密
    const str = rsa.RSAdencrypt(GetQueryString(response.config.data))
    if (response.data.data) {
      response.data.data = response.data.data.replace(/\s/g,'')
      try {
        response.data.data = JSON.parse(aes.Decrypt(response.data.data, str))
      } catch (e) {
        // TODO handle the exception
        response.data.data = aes.Decrypt(response.data.data, str)
      }
    }
    console.log(response.data,response.config.url)
    return response.data
  } else if(response.status == 200 && (response.data.code == 1030)){
    return response.data
  } else {
    if (res.code == 1015 || res.code == 1026 || res.code == 1037 || res.code == 2034 || res.code == 1004 || res.code == 1011) {
      // bug
      message.error({
        showClose: true,
        content: res.msg,
      })
      storage.remove(ACCESS_TOKEN)
      router.push('/user/login')
      // store.dispatch('user/cleanToken', '')
      // store.dispatch('user/setLoginStatus', true)
      // router.push('/home')
      return Promise.reject(new Error(`${res.code}:${res.msg}`))
    } else {
      message.error({
        content: res.msg,
        showClose: true
      })
      return Promise.reject(new Error(`${res.code}:${res.msg}`))
    }
  }
  // return response.data
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}